package com.biz.primus.management.coupon.type.tag;

import com.biz.primus.commodity.vo.BrandVo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

/**
 * 优惠券类型可用品牌选择标签
 *
 * @author david-liu
 */
@Slf4j
@Setter
public class CouponTypeBrandSelectTag extends TagSupport {
    private static final long serialVersionUID = -4147274607438476021L;

    private Boolean multiSelect;

    private Long selectedBrand;

    private List<Long> selectedBrands;

    @Override
    public int doStartTag() throws JspException {
        List<BrandVo> brandVos = new ArrayList<BrandVo>() {
            {
                BrandVo brandVo1 = new BrandVo();
                brandVo1.setBrandId(1L);
                brandVo1.setBrandName("品牌1");
                BrandVo brandVo2 = new BrandVo();
                brandVo2.setBrandId(2L);
                brandVo2.setBrandName("品牌2");
                add(brandVo1);
                add(brandVo2);
            }
        };
        JspWriter jspWriter = pageContext.getOut();
        if (Objects.nonNull(multiSelect) && multiSelect) {
            brandVos.forEach(vo -> {
                String optionHtmlText;
                if (CollectionUtils.isNotEmpty(selectedBrands) && selectedBrands.contains(vo.getBrandId())) {
                    optionHtmlText = String.format("<option value=\"%s\" selected>%s</option>", vo.getBrandId(), vo.getBrandName());
                } else {
                    optionHtmlText = String.format("<option value=\"%s\">%s</option>", vo.getBrandId(), vo.getBrandName());
                }
                try {
                    jspWriter.println(optionHtmlText);
                } catch (IOException e) {
                    log.error("out jsp content error", e);
                }
            });
        } else {
            brandVos.forEach(vo -> {
                String optionHtmlText;
                if (Objects.nonNull(selectedBrand) && Objects.equals(vo.getBrandId(), selectedBrand)) {
                    optionHtmlText = String.format("<option value=\"%s\" selected>%s</option>", vo.getBrandId(), vo.getBrandName());
                } else {
                    optionHtmlText = String.format("<option value=\"%s\">%s</option>", vo.getBrandId(), vo.getBrandName());
                }
                try {
                    jspWriter.println(optionHtmlText);
                } catch (IOException e) {
                    log.error("out jsp content error", e);
                }
            });
        }
        return super.doStartTag();
    }
}
